<template>
  <div class="login">
    <img src="/public/center.png" />
    <div class="form">
      <input
        type="text"
        v-model="username"
        placeholder="请输入测试账号user123"
      />
      <input
        type="text"
        v-model="password"
        placeholder="请输入测试密码user123"
      />
      <p class="txt">
        <span>免费注册</span>
        <span>忘记密码</span>
      </p>
      <button @click="login">登录</button>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { useLoginStore } from '@/stores/login'
import { ref } from 'vue'

const router = useRouter()
const username = ref('')
const password = ref('')

showToast({ message: '请登录' })

const useLogin = useLoginStore()
const login = async () => {
  // 修改为异步函数
  try {
    // 等待登录结果
    await useLogin.login(username.value, password.value)

    // 登录成功判断（根据实际token存储逻辑调整）
    if (localStorage.getItem('Authorization')) {
      // 替换当前历史记录并跳转，实现无法回退
      router.replace('/my')
    } else {
      showToast({
        message: '登录失败，请检查账号密码',
        type: 'error'
      })
    }
  } catch (error) {
    showToast({
      message: '登录异常，请稍后重试',
      type: 'error'
    })
    console.error('登录错误:', error)
  }
}
</script>

<style scoped>
.login {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
img {
  width: 20%;
  padding: 10%;
}
.form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
input {
  width: 90%;
  margin: 0 auto;
  padding: 5px;
}
.txt {
  width: 90%;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
}
button {
  width: 90%;
  margin: 0 auto;
  color: white;
  background-color: #db3d3c;
  border: 0px;
  padding: 10px;
}
</style>
